class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable

  include Searchable
  # include Elasticsearch::Model
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  has_many :users_roles_relations
  has_many :roles,:through => :users_roles_relations
  has_many :topics, dependent: :destroy
  has_many :replies, dependent: :destroy
  has_many :notifications

  validates :name ,uniqueness: {case_sensitive: true}

  def role?(role)
    return !!self.roles.find_by_name(role.to_s)
  end

  # 新会员是否有发帖权限
  def new_leaguer?
    return false if verified? or hr?
     return true
     # created_at >1.hour.ago
  end

  def verified?
    self.verified==true
  end
  def hr?
    self.hr==true
  end

  #关注我的人数
  def followers_count
    follower_ids.count
  end
  # 我关注的人数
  def following_count
    following_ids.count
  end


  #关注某人
  def follow_user(user)
    return false if user.blank?
    return false if  self.followed?(user)
    self.transaction do
      # 我的关注数组中添加被关注者的ID
      # self.push(following_ids: user.id)
      # self.following_ids=self.following_ids.push(user.id)
      self.following_ids += [user.id]
      self.save
      # 对方的被关注数组中添加我的ID
      # user.push(follower_ids: self.id)
      user.follower_ids += [self.id]
      user.save

      user.follower_ids.uniq!
      self.following_ids.uniq!

    end
  # notify 通知对方被关注了

  end
  # 取消关注某人
  def unfollow_user(user)
    return false if user.blank?
    # rails 事务方法 用来确保多条SQL语句要么全部执行成功、要么不执行
    self.transaction do
      self.following_ids.delete(user.id)
      self.save
      user.follower_ids.delete(self.id)
      user.save

      user.follower_ids.uniq!
      self.following_ids.uniq!
    end

  end
  # 是否关注了某人
  def followed?(user)
    return false if user.blank?
    uid= user.is_a?(User) ? user.id : user
    following_ids.include?(uid)
  end


end
User.import force: true
